<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-action:add>新建</a-button>
    </div>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
    >
        <span slot="status" slot-scope="text, record">
          <a-badge :status="record.status === '0' ? 'success' : 'default'" :text="record.status === '0' ? '启用' : '禁用'" />
        </span>
      <span slot="icon" slot-scope="text, record">
          <a-icon v-if="record.icon" :type="record.icon" />
        </span>
      <span slot="username" slot-scope="text">
          {{ text }}
        </span>
      <span slot="role_name" slot-scope="text">
        <template v-if="text">
          <template v-for="(item, index) in formatRoleName(text)">
            <a-tag color="blue" :key="index">{{ item }}</a-tag>
          </template>
        </template>
        <template v-else>
          <span>-</span>
        </template>
        </span>
      <span slot="email" slot-scope="text">
          <span>{{ text }}</span>
        </span>
      <span slot="sex" slot-scope="text, record">
          <span>{{ record.sex === '1' ? '男' : '女' }}</span>
        </span>
      <span slot="created_at" slot-scope="text">
          {{ text | dayjs }}
        </span>
      <span slot="birthday" slot-scope="text">
          {{ text | ymd }}
        </span>
      <span slot="avatar" slot-scope="text, record">
          <a-avatar v-if="record.avatar" shape="square" :src="$staticPrefix(record.avatar)" />
        </span>
      <span slot="wechat_avatar" slot-scope="text, record">
          <a-avatar v-if="record.wechat_avatar" shape="square" :src="$staticPrefix(record.wechat_avatar)" />
        </span>
      <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record, 1)" v-action:query>查看</a>
            <a-divider type="vertical" v-action:edit/>
            <a @click="handleEdit(record, 2)" v-action:edit>修改</a>
            <a-divider type="vertical" v-if="record.username !== 'admin'" v-action:delete/>
            <a @click="handleEdit(record, 3)" v-if="record.username !== 'admin'" v-action:delete>删除</a>
          </template>
        </span>
    </s-table>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getUserByDeptId as getList, add, edit, deletes } from '@/api/user'

import CreateForm from './modules/CreateForm'
import clonedeep from 'lodash.clonedeep'

const columns = [
  {
    title: '账号',
    align: 'center',
    dataIndex: 'username',
    fixed: 'left',
    scopedSlots: { customRender: 'username' }
  },
  {
    title: '昵称',
    align: 'center',
    dataIndex: 'nickName',
  },
  {
    title: '头像',
    align: 'center',
    dataIndex: 'avatar',
    scopedSlots: { customRender: 'avatar' }
  },
  {
    title: '员工号',
    align: 'center',
    dataIndex: 'no',
  },
  {
    title: '岗位',
    align: 'center',
    dataIndex: 'post_name',
  },
  {
    title: '角色',
    align: 'center',
    dataIndex: 'role_name',
    scopedSlots: { customRender: 'role_name' }
  },
  {
    title: '手机号',
    align: 'center',
    dataIndex: 'phone',
  },
  {
    title: '性别',
    align: 'center',
    dataIndex: 'sex',
    scopedSlots: { customRender: 'sex' }
  },
  {
    title: '邮箱',
    width: 150,
    align: 'center',
    dataIndex: 'email',
    scopedSlots: { customRender: 'email' }
  },
  {
    title: '状态',
    align: 'center',
    width: 100,
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'User',
  props: {
    deptId: {
      type: String,
      default: ''
    }
  },
  components: {
    STable,
    Ellipsis,
    CreateForm,
  },
  data () {
    this.columns = columns
    return {
      staticPrefix: "http://localhost:1207/static/",
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {
        id: undefined,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getList(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  mounted() {
    this.$watch('deptId', e => {
      this.queryParam.id = e;
      this.$refs.table.refresh()
    }, {
      deep: true,
      immediate: true
    })
  },
  methods: {
    formatRoleName(e) {
      if (e) {
        return Array.from(new Set(e.split(',')));
      } else {
        return ['-'];
      }
    },
    handleAdd () {
      this.mdl = {
        disabled: false
      }
      this.visible = true
    },
    handleEdit (record, index) {
      const data = clonedeep(record);
      data.role_id = data.role_id ? data.role_id.split(',').map(item => parseInt(item)) : undefined
      data.subject_id = data.subject_id && data.subject_id !== '0' ? data.subject_id.split(',').map(item => parseInt(item)) : undefined
      if (index === 1) {
        this.visible = true
        data.disabled = true;
        this.mdl = { ...data }
      } else if (index === 2) {
        this.visible = true
        data.disabled = false;
        this.mdl = { ...data }
      } else {
        this.confirmLoading = true
        deletes(data.id).then(ret => {
          this.visible = false
          this.confirmLoading = false
          // 刷新表格
          this.$refs.table.refresh()
          this.$message.info('删除成功')
        })
      }
    },
    handleOk (values) {
      const form = this.$refs.createModal
      this.confirmLoading = true
      values.subject_id = values.subject_id ? values.subject_id.join(',') : '';
      if (values.id) {
        edit(values, values.id).then(res => {
          this.visible = false
          this.confirmLoading = false
          // 重置表单数据
          form.resetFields()
          if (res.success) {
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.info('修改成功')
          } else {
            this.$message.info(res.msg)
          }
        })
      } else {
        add(values).then(res => {
          this.visible = false
          this.confirmLoading = false
          // 重置表单数据
          form.resetFields()
          if (res.success) {
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.info('新增成功')
          } else {
            this.$message.info(res.msg)
          }
        })
      }
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal
      form.resetFields() // 清理表单数据（可不做）
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
